package com.smartcommunity.service.fullSearch.impl;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.Future;
import org.apache.commons.collections.CollectionUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.sort.SortBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.alibaba.fastjson.JSON;
import com.smartcommunity.api.device.DeviceApi;
import com.smartcommunity.api.engine.EngineApi;
import com.smartcommunity.bean.entity.Camera;
import com.smartcommunity.bean.model.Pager;
import com.smartcommunity.bean.model.Result;
import com.smartcommunity.es.common.EsBasedataEnum;
import com.smartcommunity.es.common.EsIndex;
import com.smartcommunity.es.common.EsRestUtils;
import com.smartcommunity.dao.fullSearch.FullCountStatisticsDao;
import com.smartcommunity.dao.fullSearch.SearchHistoryDao;
import com.smartcommunity.dao.village.VillageDao;
import com.smartcommunity.entity.fullSearch.FullCountResponse;
import com.smartcommunity.entity.fullSearch.FullCountStatistics;
import com.smartcommunity.entity.fullSearch.FullSearchRequest;
import com.smartcommunity.entity.fullSearch.FullSearchResponse;
import com.smartcommunity.entity.fullSearch.SearchHistory;
import com.smartcommunity.entity.people.People;
import com.smartcommunity.entity.people.RealPeopleHouse;
import com.smartcommunity.entity.vehicle.EsBaseVehEntity;
import com.smartcommunity.entity.vehicle.Vehicle;
import com.smartcommunity.entity.vid.EsBaseVidEntity;
import com.smartcommunity.entity.vid.SearchModel;
import com.smartcommunity.entity.vid.VidInfo;
import com.smartcommunity.entity.village.EsHouseEntity;
import com.smartcommunity.entity.village.House;
import com.smartcommunity.service.fullSearch.FullSearchService;
import com.smartcommunity.service.people.PeopleService;
import com.smartcommunity.service.vidInfo.VidInfoService;
import com.smartcommunity.utils.BeanMapUtil;
import com.smartcommunity.utils.DateUtils;
import com.smartcommunity.utils.ExecutorUtil;
import com.smartcommunity.utils.RegExUtils;
import com.smartcommunity.utils.StringUtils;

import lombok.extern.slf4j.Slf4j;

/**
 * @ClassName: FullSearchServiceImpl 
 * @Description: 全息档案业务层
 * @author: yangyi
 * @Date: 2020/6/30 17:45
 * @Company:
 */
@Service
@Slf4j
public class FullSearchServiceImpl implements FullSearchService {

	@Autowired
	private EsRestUtils esRestUtils;
	@Autowired
    private DeviceApi deviceApi;
	@Autowired
    private EngineApi engineApi;
	@Autowired
    private VidInfoService vidInfoService;
	@Autowired
    private PeopleService peopleService;
	@Autowired
    private VillageDao villageDao;
	@Autowired
	private SearchHistoryDao searchHistoryDao;
	@Autowired
	private FullCountStatisticsDao fullCountStatisticsDao;
	
	/**
	 * 获取数据总数和今日新增数量
	 * @return
	 */
	@Override
	public FullCountResponse fullCount(List<String> villageCode, Integer userId) throws Exception {
		long st = System.currentTimeMillis();
		FullCountResponse resp = new FullCountResponse();
		String[] indexs = new String[]{EsIndex.BASEDATA};
		//实有人口-总数
		BoolQueryBuilder peopleTotalQueryBuilder = buildCountQueryBuilder(villageCode, EsBasedataEnum.PEOPLE.getIntValue());
		Future<Long> peopleTotalFuture = ExecutorUtil.executorService.submit(() -> esRestUtils.getTotalRecords(indexs, peopleTotalQueryBuilder));
		//车辆-总数
		BoolQueryBuilder vehicleTotalQueryBuilder = buildCountQueryBuilder(villageCode, EsBasedataEnum.VEHICLE.getIntValue());
		Future<Long> vehicleTotalFuture = ExecutorUtil.executorService.submit(() -> esRestUtils.getTotalRecords(indexs, vehicleTotalQueryBuilder));
		//房屋-总数
		BoolQueryBuilder houseTotalQueryBuilder = buildCountQueryBuilder(villageCode, EsBasedataEnum.HOUSE.getIntValue());
		Future<Long> houseTotalFuture = ExecutorUtil.executorService.submit(() -> esRestUtils.getTotalRecords(indexs, houseTotalQueryBuilder));
		//VID-总数
		BoolQueryBuilder vidTotalQueryBuilder = buildCountQueryBuilder(villageCode, EsBasedataEnum.VID.getIntValue());
		Future<Long> vidTotalFuture = ExecutorUtil.executorService.submit(() -> esRestUtils.getTotalRecords(indexs, vidTotalQueryBuilder));
		
		resp.setPeopleTotalCount(peopleTotalFuture.get());
		resp.setVehicleTotalCount(vehicleTotalFuture.get());
		resp.setHouseTotalCount(houseTotalFuture.get());
		resp.setVidTotalCount(vidTotalFuture.get());
		
		FullCountStatistics fullCountStatistics = fullCountStatisticsDao.getFullCountStatistics(userId);
		resp.setPeopleTodayCount(resp.getPeopleTotalCount()-fullCountStatistics.getPeopleCount());
		resp.setVehicleTodayCount(resp.getVehicleTotalCount()-fullCountStatistics.getVehicleCount());
		resp.setHouseTodayCount(resp.getHouseTotalCount()-fullCountStatistics.getHouseCount());
		resp.setVidTodayCount(resp.getVidTotalCount()-fullCountStatistics.getVidCount());
		
		long speedTime = System.currentTimeMillis() - st;
        log.info("全息档案-查询数据总量耗时:" + speedTime + "ms");
		return resp;
	}
	
	/**
	 * 构造es查询总数的参数
	 * @param villageCode
	 * @param dataType
	 * @return
	 */
	private BoolQueryBuilder buildCountQueryBuilder(List<String> villageCode, int dataType) throws Exception {
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		buildVillageCodeParam(queryBuilder, villageCode);
		queryBuilder.must(QueryBuilders.matchPhraseQuery("dataType", dataType));
		return queryBuilder;
	}
	
	/**
	 * 构造小区参数
	 * @param queryBuilder
	 */
	private void buildVillageCodeParam(BoolQueryBuilder queryBuilder, List<String> villageCode) throws Exception {
		if(CollectionUtils.isNotEmpty(villageCode)) {
			queryBuilder.must(QueryBuilders.termsQuery("villageCode", villageCode));
		}
	}
	
	/**
	 * 构造全文检索的文本搜索参数
	 * @param text
	 * @return
	 */
	private BoolQueryBuilder buildTextQueryBuilder(String text) throws Exception {
		BoolQueryBuilder textQueryBuilder = QueryBuilders.boolQuery();
		List<String> textList = RegExUtils.splitBySpaceAndPunc(text);
		if(CollectionUtils.isNotEmpty(textList)) {
			for(String item:textList) {
				BoolQueryBuilder itemQueryBuilder = QueryBuilders.boolQuery();
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("peopleName.keyword", "*"+item+"*"));   //姓名
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("plateNo.keyword", "*"+item.toUpperCase()+"*"));   //车牌号
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("detailAddress.detailAddress.keyword", "*"+item+"*"));   //小区楼栋房屋信息
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("credentialNo.keyword", "*"+item+"*"));   //证件号码
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("phoneNo.keyword", "*"+item+"*"));   //电话
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("vid.keyword", "*"+item+"*"));   //VID
				itemQueryBuilder.should(QueryBuilders.wildcardQuery("villageName.keyword", "*"+item+"*"));   //VID小区名称
				textQueryBuilder.must(itemQueryBuilder);
			}
		}
		return textQueryBuilder;
	}

	/**
	 * 全文检索
	 */
	@Override
	public Pager<FullSearchResponse> fullSearch(FullSearchRequest req, List<String> villageCode, Integer userId) throws Exception {
		try {
			saveSearchHistory(req, userId);
		}catch (Exception e) {
			log.error("全息档案保存查询历史记录错误", e);
		}
		long st1 = System.currentTimeMillis();
		String[] indexs = new String[]{EsIndex.BASEDATA};
		String text = req.getText();
		BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
		if(CollectionUtils.isNotEmpty(req.getDataType())) {
			queryBuilder.must(QueryBuilders.termsQuery("dataType", req.getDataType()));    //数据类型
		}
		buildVillageCodeParam(queryBuilder, villageCode);   //小区数据权限
		//1.文本搜索
		if(StringUtils.isNotEmpty(text)) {
			queryBuilder.must(buildTextQueryBuilder(text));
		}
		//2.图片搜索
		Map<String, Double> featureIdScoreMap = new HashMap<String, Double>();
		Map<String, Double> vidScoreMap = new HashMap<String, Double>();
		if(StringUtils.isNotEmpty(req.getImg())) {
			featureIdScoreMap = searchFeatureIdsByImg(req);
			vidScoreMap = searchVidsByImg(req);
			if(!org.springframework.util.CollectionUtils.isEmpty(featureIdScoreMap) || !org.springframework.util.CollectionUtils.isEmpty(vidScoreMap)) {
				BoolQueryBuilder imgQueryBuilder = QueryBuilders.boolQuery();
				imgQueryBuilder.should(QueryBuilders.termsQuery("featureId", featureIdScoreMap.keySet()));
				imgQueryBuilder.should(QueryBuilders.termsQuery("vid.keyword", vidScoreMap.keySet()));
				queryBuilder.must(imgQueryBuilder);
			}else {
				log.info("全息档案-图片搜索:没有匹配的视频档案");
				return new Pager<FullSearchResponse>();
			}
		}
		
		int total = esRestUtils.getTotalRecords(indexs, queryBuilder).intValue();
		List<Map<String, Object>> rows = new ArrayList<Map<String,Object>>();
		if(StringUtils.isNotEmpty(req.getImg())) {
			rows = esRestUtils.page(indexs, queryBuilder, null, 1, total, null);
		}else {
			SortBuilder sortBuilder = null;
			if(CollectionUtils.isNotEmpty(req.getDataType()) && req.getDataType().size()==1 
					&& req.getDataType().get(0).intValue()==EsBasedataEnum.VID.getIntValue()) {
				sortBuilder = esRestUtils.builderSort("lastLogTime", "desc");
			}else {
				sortBuilder = esRestUtils.builderSort("mrowTime", "desc");
			}
			rows = esRestUtils.page(indexs, queryBuilder, null, req.getPageNumber(), req.getPageSize(), sortBuilder);
		}
		long st2 = System.currentTimeMillis();
        log.info("全息档案-全文检索耗时:" + (st2-st1) + "ms");
        //3.包装数据
		if (CollectionUtils.isNotEmpty(rows)) {
            List<FullSearchResponse> resultList = new ArrayList<FullSearchResponse>();
            for(Map<String, Object> item:rows) {
            	if(item.get("dataType")!=null) {
            		FullSearchResponse resp = new FullSearchResponse();
	            	int dataType = Integer.parseInt(item.get("dataType").toString());
	            	resp.setDataType(dataType);
	            	if(dataType==EsBasedataEnum.PEOPLE.getIntValue()) {
	            		People people = JSON.parseObject(JSON.toJSONString(item), People.class);
	            		resp.setPeople(people);
	            	}else if(dataType==EsBasedataEnum.VEHICLE.getIntValue()) {
	            		EsBaseVehEntity esBaseVehEntity = JSON.parseObject(JSON.toJSONString(item), EsBaseVehEntity.class);
	            		Vehicle vehicle = EsBaseVehEntity.parseTo(esBaseVehEntity, villageCode);
	            		resp.setVehicle(vehicle);
	            	}else if(dataType==EsBasedataEnum.HOUSE.getIntValue()) {
	            		EsHouseEntity esHouse = JSON.parseObject(JSON.toJSONString(item), EsHouseEntity.class);
	            		House house = EsHouseEntity.parseTo(esHouse, villageCode);
	            		resp.setHouse(house);
	            	}else if(dataType==EsBasedataEnum.VID.getIntValue()) {
	            		EsBaseVidEntity esVidinfo = JSON.parseObject(JSON.toJSONString(item), EsBaseVidEntity.class);
	            		VidInfo vidinfo = EsBaseVidEntity.parseTo(esVidinfo);
	            		resp.setVidInfo(vidinfo);
	            	}
	            	resultList.add(resp);
            	}
            }
            if(CollectionUtils.isNotEmpty(resultList)) {
            	buildPeople(resultList, villageCode);
            	buildHouse(resultList);
	            buildVid(resultList);
	            if(StringUtils.isNotEmpty(req.getImg())) {
	            	buildImgSearchScore(resultList, featureIdScoreMap, vidScoreMap);
	            	resultList = pageImgSearchResult(resultList, req.getPageNumber(), req.getPageSize());
	            }
            }
            long st3 = System.currentTimeMillis();
            log.info("全息档案-包装数据耗时:" + (st3-st2) + "ms");
            return new Pager<FullSearchResponse>(req.getPageNumber(), req.getPageSize(), total, resultList);
        }
		return new Pager<FullSearchResponse>();
	}
	
	/**
	 * 图片base64搜索实有人口
	 * @param req
	 * @return
	 */
	private Map<String, Double> searchFeatureIdsByImg(FullSearchRequest req) throws Exception {
		Map<String, Double> featureIdScoreMap = new HashMap<String, Double>();
		Map<String, Object> param = new HashMap<>();
		param.put("imageData", req.getImg());
		param.put("threshold", req.getThreshold());
		param.put("topN", req.getTopN());
		Result<List<Map<String, Object>>> feignResult = engineApi.getPersonsByImage(param);
		if (null != feignResult && feignResult.isOk() && CollectionUtils.isNotEmpty(feignResult.getData())) {
			feignResult.getData().forEach(item->{
				if(item.get("featureId")!=null && item.get("dist")!=null) {
					featureIdScoreMap.put(item.get("featureId").toString(), Double.valueOf(item.get("dist").toString()));
				}
			});
		}
		return featureIdScoreMap;
	}
	
	/**
	 * 图片base64搜索VID视频档案
	 * @param req
	 * @return
	 */
	private Map<String, Double> searchVidsByImg(FullSearchRequest req) throws Exception {
		Map<String, Double> vidScoreMap = new HashMap<String, Double>();
		Map<String, Object> param = new HashMap<>();
		param.put("imageData", req.getImg());
		param.put("threshold", req.getThreshold());
		param.put("topN", req.getTopN());
		Result<Map<String, Object>> feignResult = engineApi.searchVidsByUrl(param);
		if (null != feignResult && feignResult.isOk() && !org.springframework.util.CollectionUtils.isEmpty(feignResult.getData())
				&& feignResult.getData().get("values")!=null) {
			List<Map<String, Object>> values = (List<Map<String, Object>>) feignResult.getData().get("values");
			if(CollectionUtils.isNotEmpty(values)) {
				values.forEach(item->{
					if(item.get("vid")!=null && item.get("dist")!=null) {
						vidScoreMap.put(item.get("vid").toString(), Double.valueOf(item.get("dist").toString()));
					}
				});
			}
		}
		return vidScoreMap;
	}
	
	/**
	 * 构建实有人口的最后出现天数/居住地址
	 * @param list
	 * @param villageCode
	 * @throws Exception 
	 */
	private void buildPeople(List<FullSearchResponse> list, List<String> villageCode) throws Exception {
		StringBuffer vids = new StringBuffer();
		for(FullSearchResponse item:list) {
			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.PEOPLE.getIntValue() && !StringUtils.isEmpty(item.getPeople().getVid())) {
				vids.append(item.getPeople().getVid()).append(",");
			}
		}
		if(vids.length()>0) {
			SearchModel model = new SearchModel();
            model.setVid(vids.toString().split(","));
            model.setPage(0);
            model.setPageSize(list.size());
            List<VidInfo> vidList = vidInfoService.listVidInfo(model);
            if(CollectionUtils.isNotEmpty(vidList)) {
            	for (VidInfo vidInfo : vidList) {
            		for(FullSearchResponse item:list) {
            			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.PEOPLE.getIntValue() 
            					&& !StringUtils.isEmpty(item.getPeople().getVid()) && vidInfo.getVid().trim().equals(item.getPeople().getVid().trim())) {
            				Long lastTime = vidInfo.getLastLogTime();
                            if (lastTime!=null && lastTime.longValue()!=0) {
                                item.getPeople().setLastDay(DateUtils.getDateDaySpace(new Date(), new Date(lastTime)));
                            }
                            item.setVidInfo(vidInfo);
                            break;
            			}
            		}
            	}
            }
		}
		
		for(FullSearchResponse item:list) {
			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.PEOPLE.getIntValue()
					&& CollectionUtils.isNotEmpty(item.getPeople().getDetailAddress())) {
				for(RealPeopleHouse house:item.getPeople().getDetailAddress()) {
					if(CollectionUtils.isEmpty(villageCode) || villageCode.contains(house.getVillageCode())) {
						item.getPeople().setVillageCode(house.getVillageCode());
						item.getPeople().setBuildingNo(house.getBuildingNo());
						item.getPeople().setUnitNo(house.getUnitNo());
						item.getPeople().setHouseNo(house.getHouseNo());
						item.getPeople().setResidenceAddress(house.getDetailAddress());
						break;
					}
				}
			}
		}
	}
	
	/**
	 * 构建房屋人数和所属辖区
	 * @param list
	 * @throws Exception
	 */
	private void buildHouse(List<FullSearchResponse> list) throws Exception {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		Set<String> villageCodes = new HashSet<String>();
		for(FullSearchResponse item:list) {
			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.HOUSE.getIntValue()
					&& StringUtils.isNotEmpty(item.getHouse().getVillageCode())) {
				villageCodes.add(item.getHouse().getVillageCode());
				paramMap.put("villageCode", item.getHouse().getVillageCode());
				paramMap.put("buildingNo", item.getHouse().getBuildingNo());
				paramMap.put("unitNo", item.getHouse().getUnitNo());
				paramMap.put("houseNo", item.getHouse().getHouseNo());
				item.getHouse().setRealPeoples(villageDao.listPeopleByHouse(paramMap));
			}
		}
		if(CollectionUtils.isNotEmpty(villageCodes)) {
			List<Map<String, Object>> orgNameList = villageDao.getOrgNamesByVillageCodes(villageCodes);
			Map<String, Object> orgNameMap = new HashMap<String, Object>();
			for(Map<String, Object> tmp:orgNameList) {
				if(tmp.get("villageCode")!=null && tmp.get("orgName")!=null) {
					orgNameMap.put(tmp.get("villageCode").toString(), tmp.get("orgName").toString());
				}
			}
			for(FullSearchResponse item:list) {
				if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.HOUSE.getIntValue()
						&& StringUtils.isNotEmpty(item.getHouse().getVillageCode())
						&& orgNameMap.containsKey(item.getHouse().getVillageCode())) {
					item.getHouse().setOrgName(orgNameMap.get(item.getHouse().getVillageCode()).toString());
				}
			}
		}
	}
	
	/**
	 * 构建VID的最后出现天数和摄像机名称
	 * @param list
	 */
	private void buildVid(List<FullSearchResponse> list) throws Exception {
		StringBuffer vids = new StringBuffer();
		Set<String> cameraIds = new HashSet<>();
		Map<String, Camera> cameraMap = new HashMap<String, Camera>();
		for(FullSearchResponse item:list) {
			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.VID.getIntValue()) {
				cameraIds.add(item.getVidInfo().getLastCameraId());
				vids.append(item.getVidInfo().getVid()).append(",");
			}
		};
		//摄像机名称
        try {
        	if(CollectionUtils.isNotEmpty(cameraIds)) {
	        	//查询相机信息
	            Map<String, Object> cameraSearchParam = new HashMap<>();
	            cameraSearchParam.put("deviceIds", String.join(",", cameraIds));
	            List<Camera> cameraList = deviceApi.getCameraList(cameraSearchParam).getData();
	            //改map集合
	            cameraMap = BeanMapUtil.mapBean(cameraList, "cameraId");
        	}
        } catch (Exception e) {
            log.error("全息档案查询设备信息错误", e);
        }
        if(!org.springframework.util.CollectionUtils.isEmpty(cameraMap)) {
        	for(FullSearchResponse item:list) {
        		if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.VID.getIntValue() && cameraMap.containsKey(item.getVidInfo().getLastCameraId())) {
        			item.getVidInfo().setCameraName(cameraMap.get(item.getVidInfo().getLastCameraId()).getName());
        		}
        	}
        }
        //最后出现天数
        if(vids.length()>0) {
        	People peopleParam = new People();
        	peopleParam.setVid(vids.toString().substring(0, vids.length()-1));
        	List<People> peopleList = peopleService.listPeoplesForFullSearch(peopleParam, 1, vids.toString().split(",").length).getList();
        	if(CollectionUtils.isNotEmpty(peopleList)) {
        		for(People people:peopleList) {
	        		for(FullSearchResponse item:list) {
	        			if(item.getDataType()!=null && item.getDataType().intValue()==EsBasedataEnum.VID.getIntValue()
        					&& StringUtils.isNotEmpty(people.getVid()) && item.getVidInfo().getVid().trim().equals(people.getVid().trim())) {
    						Long lastTime = item.getVidInfo().getLastLogTime();
                            if (lastTime!=null && lastTime.longValue()!=0) {
                                people.setLastDay(DateUtils.getDateDaySpace(new Date(), new Date(lastTime)));
                            }
                            item.setPeople(people);
                            break;
    					}
        			}
        		}
        	}
        }
	}
	
	/**
	 * 构建图片搜索分数
	 * @param resultList
	 * @param vidScoreMap
	 */
	private void buildImgSearchScore(List<FullSearchResponse> resultList, Map<String, Double> featureIdScoreMap, Map<String, Double> vidScoreMap) {
		boolean hasDist = false;
		if(!org.springframework.util.CollectionUtils.isEmpty(featureIdScoreMap) || !org.springframework.util.CollectionUtils.isEmpty(vidScoreMap)) {
			for(FullSearchResponse item:resultList) {
				if(item.getPeople()!=null && !StringUtils.isEmpty(item.getPeople().getFeatureId())
						&& featureIdScoreMap.get(item.getPeople().getFeatureId())!=null) {
					hasDist = true;
					item.setDist(featureIdScoreMap.get(item.getPeople().getFeatureId()));
				}
				if(item.getVidInfo()!=null && !StringUtils.isEmpty(item.getVidInfo().getVid())
						&& vidScoreMap.get(item.getVidInfo().getVid())!=null) {
					hasDist = true;
					item.setDist(vidScoreMap.get(item.getVidInfo().getVid()));
				}
			}
		}
		//按相似度降序排列
		if(hasDist) {
			Collections.sort(resultList, (FullSearchResponse o1, FullSearchResponse o2) -> Double.compare(o2.getDist(), o1.getDist())==0?Integer.compare(o2.getDataType(), o1.getDataType()):Double.compare(o2.getDist(), o1.getDist()));
		}
	}
	
	/**
	 * 图片搜索结果做内存分页
	 * @param resultList
	 * @return
	 */
	private List<FullSearchResponse> pageImgSearchResult(List<FullSearchResponse> resultList, Integer pageNumber, Integer pageSize) {
		if(resultList.size()<=(pageNumber-1)*pageSize) {
			return new ArrayList<FullSearchResponse>();
		}else if(resultList.size()<=pageNumber*pageSize) {
			return resultList.subList((pageNumber-1)*pageSize, resultList.size());
		}else {
			return resultList.subList((pageNumber-1)*pageSize, pageNumber*pageSize);
		}
	}
	
	/**
	 * 保存搜索历史
	 * @param req
	 * @param userId
	 */
	private void saveSearchHistory(FullSearchRequest req, Integer userId) throws Exception {
		if(StringUtils.isEmpty(req.getText()) && StringUtils.isEmpty(req.getImg())) return;
		SearchHistory searchHistory = new SearchHistory();
		searchHistory.setUserId(userId);
		searchHistory.setText(req.getText());
		searchHistory.setImg(req.getImg());
		searchHistory.setMrowTime(new Date());
		//先删除该用户相同内容的搜索历史记录
		searchHistoryDao.delSearchHistory(searchHistory);
		searchHistoryDao.saveSearchHistory(searchHistory);
	}
	
}
